<?php

/**
 * This class represents a facet
 *
 * @author Rob Young <rob@roryoung.co.uk>
 * @package forage.features.faceting
 */
class ForageFacet implements IteratorAggregate
{
  /**
   * The name of the field which this facet applies to
   *
   * @var string
   */
  private $field;

  /**
   * The values which are available for this facet
   *
   * @var array of ForageFacetValue objects
   */
  private $values;

  /**
   * Class constructor
   */
  public function __construct($field)
  {
    $this->field = $field;
  }

  /**
   * Magic accessor for 'field' and 'values'
   *
   * @param string $name
   * @return mixed
   */
  public function __get($name)
  {
    switch ($name) {
    case 'field':
    case 'values':
      return $this->$name;
    case 'is_filter':
      return $this->isFilter();
    case 'filter_values':
      return $this->getFilterValues();
    }
  }

  /**
   * By default iterate over the facet's values
   *
   * @return array
   */
  public function getIterator()
  {
    return new ArrayIterator($this->values);
  }

  /**
   * Add a value to this facet
   *
   * @param string $value
   * @param int $count
   * @param bool $filter
   */
  public function addValue($value, $count, $filter=false)
  {
    $this->values[] = new ForageFacetValue($value, $count, $filter);
  }

  /**
   * Whether this facet is currently being filtered on
   *
   * @return bool
   */
  public function isFilter()
  {
    foreach ($this->values as $value) {
      if ($value->filter) {
        return true;
      }
    }
    return false;
  }

  /**
   * Return the ForageFacetValue which is currently being filtered on,
   * if there is one.
   *
   * @return ForageFacetValue
   */
  public function getFilterValues()
  {
    $values = array();
    foreach ($this->values as $value) {
      if ($value->filter) {
        $values[] = $value;
      }
    }
    return $values;
  }
}

/**
 * Class to represent a facet value
 *
 * @author Rob Young <rob@roryoung.co.uk>
 * @package forage.features.faceting
 */
class ForageFacetValue
{
  /**
   * The value of this err... value.
   *
   * @var string
   */
  private $value;

  /**
   * The number of times this value appears in the result
   * (this number which would apear next to the facet value)
   *
   * @var int
   */
  private $count;

  /**
   * True if this value is being used as a filter for it's facet
   *
   * @var bool
   */
  private $filter;

  /**
   * Class constructor
   */
  public function __construct($value, $count, $filter=false)
  {
    $this->value = $value;
    $this->count = $count;
    $this->filter= $filter;
  }

  /**
   * Magic accessor for object properties
   */
  public function __get($name)
  {
    switch ($name) {
    case 'value':
    case 'count':
    case 'filter':
      return $this->$name;
    }
  }
  
  /**
   * String representation of this object
   */
  public function __toString()
  {
    return $this->value;
  }
}
